package com.shi.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shi.Dao.UserDao;
import com.shi.entity.User;

public class UserServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		String task = request.getParameter("task");
		if("".equals(task)||task==null){
			login(request, response);
		}else if("login".equals(task)){
			tologin(request, response);
		}else{
			response.sendError(404);
		}
	}
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
		
	}
	private void tologin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserDao dao = new UserDao();
		User user = dao.findUserByNameAndPassword(name, password);
		
		HttpSession session = request.getSession();
		if(user != null){
			session.setAttribute("user", user);
			if(user.getRole().equals("admin")){
				response.sendRedirect("sell.html?task=selllist");
			}else{
				response.sendRedirect("/WEB-INF/views/add.jsp");
			}
		}else{
			response.sendRedirect("index.jsp?state=-10000");
		}
	}
}
